import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'
import Cookies from 'js-cookie'

Vue.use(VueRouter)

const originalPush = VueRouter.prototype.push
// 修改 原型对象中的push方法
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}

const mapRoleToRoute = new Map([
  ['超级管理员', 'graphiting'],
  ['石墨化库管', 'graphiting'],
  ['浸渍库管', 'steep'],
  ['隧道窑库管', 'tunnel']
])

const routes = [
  {
    path: '/',
    redirect: '/layout'
  },
  {
    path: '/layout',
    name: 'layout',
    component: () => import('@/layout'),
    redirect: `/steep`,
    children: [
      {
        path: '/steep',
        name: 'steep',
        component: () => import('@/views/steep.vue')
      },
      {
        path: '/graphiting',
        name: 'graphiting',
        component: () => import('@/views/graphiting.vue')
      },
      {
        path: '/tunnel',
        name: 'tunnel',
        component: () => import('@/views/tunnel.vue')
      },

      {
        path: '/profiling',
        name: 'profiling',
        component: () => import('@/views/profiling.vue')
      },
      {
        path: '/naturalGas',
        name: 'naturalGas',
        component: () => import('@/views/naturalGas.vue')
      },
      {
        path: '/calcination',
        name: 'calcination',
        component: () => import('@/views/calcination.vue')
      },
      {
        path: '/crucible',
        name: 'crucible',
        component: () => import('@/views/crucible.vue')
      }
    ]
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

router.beforeEach((to, from, next) => {
  const token = Cookies.get('token')
  // console.log('打印一下cookie', Cookies.get('role'), mapRoleToRoute.get(Cookies.get('role')))
  if (token) {
    sessionStorage.setItem('Token', JSON.stringify(token))
    // console.log('to.fullPath', to.fullPath)
    var { fullPath } = to
    // if (fullPath === '/layout') {
    //   // console.log('5-----', `/${mapRoleToRoute.get(Cookies.get('role'))}`)
    //   next(`/${mapRoleToRoute.get(Cookies.get('role'))}`)
    // } else {
    next()
    store.commit('saveCurrentPage', fullPath)
    // }
  } else {
    // const ports = window.location.port.slice(0, 2)
    // window.location.href = 'http://106.52.170.16:8401/'
    window.location.href = 'http://101.42.233.226:8401/'
  }
})

export default router
